<?php

namespace Modules\Asset\Entities;

use Modules\Core\Entities\BaseEntity as Model;
use ThrowException;

use Modules\Order\Traits\Skuable;
use Modules\Asset\Entities\PackageSku;
use Modules\Market\Entities\Tenant;

use Setting;

use DB;

class Resale extends Model
{
    use Skuable;

    protected $guarded = [];
    protected $table = 'resale_records';
    static public $resourceName = '转售';

    // 不用扣库
    public $skipReduceStock = true;

    protected $appends = ['union_status', 'union_status_text'];


    public function scopeSearch($query, $key)
    {

        $query = $query->where('sid', $key);

        $query->orWhereHas('user', function ($q) use ($key) {
            return $q->where('name', $key)->orWhere('phone', $key);
        });

        return $query;
    }

    public function getType($type = 'node_type') 
    {
        $map = [
            'base_sku_type' => 'resale',
            'node_type' => 'resale'
        ];

        return @$map[$type];
    }

    // 统一状态
    public function getUnionStatusAttribute()
    {
        $status = 'unknow';

        $map = [
            1 => 'pending',
            2 => 'completed',
            3 => 'expired',
            4 => 'closed',
            5 => 'pay_pending'
        ];

        return $map[$this->status];
    }

    // 统一状态
    public function getUnionStatusTextAttribute()
    {
         $map = [
            'pending' => '出售中',
            'completed' => '已完成',
            'expired' => '已过期',
            'closed' => '已关闭',
            'pay_pending' => '交易中',
        ];

        return $map[$this->union_status];
    }

    // 状态筛选
    public function scopeStatus($query, $status)
    {
        if ($status === 'all') {
            return $query;
        };
        
        $statusMap = [
           'pending' => 1,
            'completed' => 2,
            'expired' => 3,
            'closed' => 4,
            'pay_pending' => 5,
        ];
        return $query->where('status', $statusMap[$status]);
    }

    // 发起用户
    public function user()
    {
        return $this->belongsTo('\Modules\User\Entities\User', 'user_id');
    }

    // 购买用户
    public function buyer()
    {
        return $this->belongsTo('\Modules\User\Entities\User', 'buyer_id');
    }

    // 物品
    // public function package_sku()
    // {
    //     return $this->belongsTo('\Modules\Asset\Entities\PackageSku', 'package_sku_id');
    // }

    public function package_skus()
    {
        return $this->belongsToMany('\Modules\Asset\Entities\PackageSku', 'resale_package_sku');
    }

    // package
    public function package()
    {
        return $this->belongsTo('\Modules\Asset\Entities\Package', 'package_id');
    }

    // 生成 sid
    public function generateSid()
    {
        $this->update([
            'sid' => 'R' . (113000 + $this->id)
        ]);
    }

    // 多个物品创建转售 (批量创建目前仅支持使用统一建议价挂售)
    static public function createWithPackageSkus($user, $skus, $options = []) 
    {

        // 所有物品id数组
        $skuIds = $skus->pluck('id');

        // 总转售价
        $moneySum = 0;
        $scoreSum = 0;
        $skuTotal = 0;

        foreach ($skus as $sku) {
            if ($sku->union_status !== 'pending') {
                return false;
            }

            // 计算建议挂售价
            list($money, $redpack, $score) = $sku->calcReturnSaleInfo();

            $moneySum += $money + $redpack;
            $scoreSum += $score;
            $skuTotal += $sku->total;

            // $this->update([
            //     'status' => 5
            // ]);
        }

        // 生成转售记录
        $record = Resale::create([
            'user_id' => $user->id,
            // 'package_sku_id' => $this->id,
            'resale_type' => 'package_sku',
            'product_total' => $skuTotal,
            'money_price' => $moneySum,
            'score_price' => $scoreSum,
            'limit_phone' => @$optoins['limit_phone'],
            'is_allow_fast_match' =>  1       
        ]);

        $record->generateSid();

        $record->package_skus()->sync($skuIds);

        PackageSku::whereIn('id', $skuIds)->update([
            'resale_id' => $record->id,
            'status' => 5
        ]);

        return $record;
    }

    // 某商购买
    public function completeWithTenant($tenant, $completeType = 2)
    {
        $this->refresh();

        DB::beginTransaction();

        $order = NULL;

        if ($this->union_status !== 'pending') {
            return false;
        }

        // package
        if ($this->resale_type  === 'package') {
            // 完成转售
            $this->package->completeResale($this, $order);
        }
        elseif ($this->resale_type === 'package_sku') {
            // 完成转售
            foreach ($this->package_skus as $packageSku) {
                $packageSku->completeResaleForTenant($this, $order);
            }
        }

        // 是否要扣除商户的资产余额， 
        // 默认为不扣除，扣除的话会使asset_records表数据量快速增长
        $shouldChangeTenantAsset = false;
        if ($shouldChangeTenantAsset) {
            // 扣除商户红包
            if ($this->money_price) {
                $tenant->user->asset('redpack')->out($this->money_price, [
                    'description' => '购买转售商品-' . ($this->sid),
                    'order' => $order
                ]) ?: ThrowException::Conflict('商户红包余额不足~');
            }

            // 扣除商户积分
            if ($this->score_price) {
                $tenant->user->asset('score')->out($this->score_price, [
                    'description' => '购买转售商品-' . ($this->sid),
                    'order' => $order
                ]) ?: ThrowException::Conflict('商户积分不足~');
            }
        }

        // 划转红包给转售用户
        if ($this->money_price) {
            $this->user->asset('redpack')->in($this->money_price, [
                'description' => '发货-' . ($this->sid),
                'order' => $order
            ]) ?: ThrowException::Conflict('服务器忙，请重试~');;
        }

        // 划转积分给转售用户
        if ($this->score_price) {
            $this->user->asset('score')->in($this->score_price, [
                'description' => '发货-' . ($this->sid),
                'order' => $order
            ]) ?: ThrowException::Conflict('服务器忙，请重试~');
        }

        // \Log::error('comple');

        $this->update([
            'complete_type' => $completeType,
            'tenant_id' => $tenant->id,
            'buyer_id' => $tenant->user_id,
            'status' => 2,
            'complete_at' => now(),
            'order_id' => @$order->id
        ]);

        DB::commit();

        $tenant->updateStat();

        return true;
    }

    // 完成转售
    public function complete($order)
    {
        $this->refresh();

        DB::beginTransaction();

        if ($this->union_status !== 'pending') {
            return false;
        }

        // package
        if ($this->resale_type  === 'package') {
            // 完成转售
            $this->package->completeResale($this, $order);
        }
        elseif ($this->resale_type === 'package_sku') {
            // 完成转售
            foreach ($this->package_skus as $packageSku) {
                $packageSku->completeResale($this, $order);
            }
            // $this->package_sku->completeResale($this, $order);
        }

        // 划转红包给转售用户
        if ($this->money_price) {
            $this->user->asset('redpack')->in($this->money_price, [
                'description' => '转售获得',
                'order' => $order
            ]);
        }

        // 划转积分给转售用户
        if ($this->score_price) {
            $this->user->asset('score')->in($this->score_price, [
                'description' => '转售获得',
                'order' => $order
            ]);
        }

        // \Log::error('comple');

        $this->update([
            'status' => 2,
            'complete_at' => now(),
            'order_id' => $order->id
        ]);

        DB::commit();

        return true;
    }

    public function close($force = false)
    {
        if (!$force && $this->status !== 1) {
            return false;
        }

        foreach ($this->package_skus as $packageSku) {
            $packageSku->cancelResale();
        }
        // $this->package_sku->cancelResale();

        $this->update([
            'status' => 4
        ]);

        // $this->delete();

        return true;
    }

    static public function beforeGetList($options)
    {
        if (@$options['status']) {
            $options['scopes']['status'] = $options['status'];
        }

        if (@$options['match_type']) {
            $options['where']['is_allow_fast_match'] = $options['match_type'] == 2 ? 1 : 0;
        }

        return $options;
    }

    // 生成order sku信息
    public function generateSkuInfo()
    {
        $title = '';
        $thumb = '';
        $total  = 1;

        if ($this->resale_type === 'package') {
            $title = @$this->package->title;
            $thumb = @$this->package->thumb;
        }
        elseif ($this->resale_type === 'package_sku') {
            $title = @$this->package_sku->title . 'X' . $total . '件';
            $thumb = @$this->package_sku->thumb;
        }

        return [
            'sku_id' => $this->id,
            'sku_uuid' => $this->uuid,
            'node_uuid' => NULL,
            'node_id' => NULL,
            'node_type' => $this->getType(),
            'base_sku_type' => $this->getType('base_sku_type'),
            'sku_type' => 1,
            'is_hidden_sku' => 0,
            'activity_id' => NULL,
            'title' => $title,
            'thumb' => $thumb,
            'number' => '',
            'group_price_title' => '',
            'attrs' => [],
            'money_price' => $this->money_price,
            'discount_money_price' => $this->money_price,
            'score_price' => $this->score_price,
            'discount_score_price' => $this->score_price,
        ];
    }

    // 尝试自动购买
    public function tryAutoBuy()
    {
        $this->refresh();

        if (!$this->is_allow_fast_match || $this->union_status !== 'pending') {
            return false;
        }

        $isAutoBuy = intVal(@Setting::get('sys_market')['is_auto_buy'] ?: 0);

        if ($isAutoBuy) {
            $tenantId = intVal(@Setting::get('sys_market')['auto_buy_tenant_id'] ?: 0);
            $tenant = Tenant::getEntity([
                'id' => $tenantId
            ], false);

            if ($tenant) {
                // 3为自动购买
                $this->completeWithTenant($tenant, 3);
            }
        }
    }

}
